import re

from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from answers.models import QuesUserModel, LabelUserModel, QuesModel, LabelModel, CommentModel
from tucao.models import Tucao, Collections
from users.models import User, UserDetail, Company, School, Exp, Dynamics


class SMSCodeSerializers(serializers.Serializer):
    '''短信验证码'''

    pass


class RegisterSerializers(serializers.ModelSerializer):
    '''创建用户的序列器'''
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='JWT token', read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'mobile', 'sms_code', 'allow', 'token')
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 6,
                'max_length': 16,
                'error_messages': {
                    'min_length': '仅允许6-16个字符的密码',
                    'max_length': '仅允许6-16个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        '''验证手机号'''
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def validate_allow(self, value):
        '''检验用户是否同意协议'''
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    def validate(self, data):
        # 判断短信验证码
        redis_conn = get_redis_connection('verify_codes')
        mobile = data['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        if real_sms_code is None:
            raise serializers.ValidationError('无效的短信验证码')
        if data['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return data

    def create(self, validated_data):

        # 移除数据库中不存在的属性
        del validated_data['sms_code']
        del validated_data['allow']
        user = super().create(validated_data)
        # 调用django的认证系统加密密码
        user.nick_name = validated_data['username']
        user.set_password(validated_data['password'])
        user.save()
        UserDetail.objects.create(user=user)
        Company.objects.create(user=user)
        School.objects.create(user=user)

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user


class ExpcationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Exp
        fields = "__all__"


class CompanySettingSerializers(serializers.ModelSerializer):
    class Meta:
        model = Company
        fields = ("id", "company", "profession", "user_id")

    def update(self, instance: User, validated_data):
        # print(validated_data)
        # options=['nick_name','email','mobile','password','avatar_url', "school_name", "professional", "company", "profession"]
        Company.objects.filter(id=instance.id).update(**validated_data)
        instance.refresh_from_db()
        return instance


class SchoolSettingSerializers(serializers.ModelSerializer):
    class Meta:
        model = School
        fields = ("id", "school_name", "professional", "user_id")
        extra_kwargs = {
            "id": {'required': False},
            "user_id": {'required': False},
            "school_name": {'required': False},
            "professional": {'required': False},
        }

    def update(self, instance: User, validated_data):
        print(validated_data)
        # options=['nick_name','email','mobile','password','avatar_url', "school_name", "professional", "company", "profession"]
        School.objects.filter(id=instance.id).update(**validated_data)
        instance.refresh_from_db()
        return instance


# 更新userdetail表数据序列化器
class UserDetailSerializers(serializers.ModelSerializer):
    class Meta:
        model = UserDetail
        fields = '__all__'

    def update(self, instance, validated_data):
        UserDetail.objects.filter(id=instance.id).update(**validated_data)
        instance.refresh_from_db()
        return instance


class UserCenterSerializers(serializers.ModelSerializer):
    detail = UserDetailSerializers()
    company = CompanySettingSerializers()
    school = SchoolSettingSerializers()

    class Meta:
        model = User
        fields = ("id", "nick_name", "email", "mobile", "password", 'detail', "username", 'company', 'school')
        # 调用django的认证系统加密密码

        #


# 更新user表数据序列化器

class AccountSettingSerializers(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ("id", "nick_name", "email", "mobile", "password", "avatar_url")
        extra_kwargs = {
            "password": {
                'required': False,
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }}
        }

    def update(self, instance: User, validated_data):
        # print(validated_data)
        # options=['nick_name','email','mobile','password','avatar_url', "school_name", "professional", "company", "profession"]
        User.objects.filter(id=instance.id).update(**validated_data)
        instance.refresh_from_db()
        return instance


class IntroduceRelated(serializers.RelatedField):
    def to_representation(self, value):
        count=0
        mydict=value.__dict__
        print(mydict)
        list=['_state','_user_cache',"id","user_id"]
        for key in mydict:
            if key in list:
                continue
            # if mydict.get(key,None):
            if mydict.get(key,None):
                count += 1

        # print(count)
        return count


class UserEditSettingSerializers(serializers.ModelSerializer):
    detail=IntroduceRelated(read_only=True)
    company=IntroduceRelated(read_only=True)
    school=IntroduceRelated(read_only=True)
    exp=IntroduceRelated(many=True,read_only=True)
    user=IntroduceRelated(read_only=True)
    class Meta:
        model = User
        fields = (
        "id", "nick_name", "email", "mobile", "password", "avatar_url", "username", "detail", "company", "school",
        "exp","user")
        extra_kwargs = {
            "password": {
                'required': False,
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }}
        }


class UserEditDetailSerializers(serializers.ModelSerializer):
    class Meta:
        model = UserDetail
        fields = ("id", "user_id", "web_site", "hometown", "birthday", "gender", "city")


class EduUpdateserializer(serializers.ModelSerializer):
    pass


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'nick_name')


class DynamicsSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)

    class Meta:
        model = Dynamics
        fields = ("id", 'user', 'category', 'content', 'label', 'create_time', 'title', 'contact_id')
        read_only = ('create_time',)


class QuestionsSerializer(serializers.ModelSerializer):
    """用户关注问题"""
    class Meta:
        model = QuesModel
        fields = "__all__"


class UserQuestionsSerializer(serializers.ModelSerializer):
    ques = QuestionsSerializer(read_only=True)

    class Meta:
        model = QuesUserModel
        fields = ('id', 'ques')


class LabelsSerializer(serializers.ModelSerializer):
    class Meta:
        model = LabelModel
        fields = "__all__"


class UserLabelsSerializer(serializers.ModelSerializer):
    label = LabelsSerializer(read_only=True)

    class Meta:
        model = LabelUserModel
        fields = ('id', 'label')


class TucaosSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tucao
        fields = "__all__"


class UserTucaosSerializer(serializers.ModelSerializer):
    tucao = TucaosSerializer(read_only=True)

    class Meta:
        model = Collections
        fields = ('id', 'tucao')


class UserAnswersSerializer(serializers.ModelSerializer):
    class Meta:
        model = CommentModel
        fields =('id','ques','user','content')

class MyQuestionsSerializer(serializers.ModelSerializer):
    """我的提问"""
    class Meta:
        model = QuesModel
        fields = "__all__"


